<template>
  <el-dialog title="选择代理" :visible.sync="localOpen" width="800px" :close-on-click-modal="true" @close="cancel"
    append-to-body>
    <div>
      <el-form :model="selectAgentQueryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="selectAgentQueryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="代理商名称" prop="agentName">
          <el-input v-model="selectAgentQueryParams.agentName" placeholder="请输入代理商名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="代理商等级" prop="gradeName">
          <el-input v-model="selectAgentQueryParams.gradeName" readonly="readonly" placeholder="请输入代理商等级"
            @click.native="openSelectGrade(1)" clearable />
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="selectAgentQueryParams.tel" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="上线" prop="state">
          <el-select v-model="selectAgentQueryParams.state" placeholder="请选择上线" clearable>
            <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="省、市、区" prop="queryProvinceAndCityAndDistrict">
          <el-cascader placeholder="请选择省、市、区" v-model="selectAgentQueryParams.queryProvinceAndCityAndDistrict" :options="options"
            @keyup.enter.native="handleQuery" @lazy-load="selectLoadOptions"
            :props="{ lazy: true,checkStrictly:true,multiple: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }"
            clearable></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>


      <el-table v-loading="loading" :data="agentList" ref="agentListTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="代理商" align="center" prop="agentName" />
        <el-table-column label="等级" align="center" prop="gradeName" />
        <el-table-column label="联系人" align="center" prop="contacts" />
        <el-table-column label="联系电话" align="center" prop="tel" />
        <el-table-column label="省、市、区" align="center" prop="provinceAndCityAndDistrict" />
        <el-table-column label="详细地址" align="center" prop="address" />
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="selectAgentQueryParams.pageNum" :limit.sync="selectAgentQueryParams.pageSize"
        @pagination="getList" />
      <!-- 选择等级 -->
      <SelectGrade ref="selectGrade" :open="gradFlag" @selected-data="selectedGradeData"
        @close-select-window="closeSelectGrade" />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="selectData">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    listAgent,
  } from "@/api/bus_web/agent/agent";
  import {
    loadOptions
  } from "@/api/system/sys_region";
  import SelectGrade from "../grade/select.vue";
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  export default {
    name: "SelectAgent",
    dicts: ['common_state'],
    props: {
      open: Boolean
    },
    components: {
      SelectGrade
    },
    data() {
      return {
        localOpen: this.open,
        options: [],
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 代理商管理表格数据
        agentList: [],
        agentListTable:[],
        // 弹出层标题
        title: "",
        // 是否显示等级选择
        gradFlag: false,
        // 查询参数
        selectAgentQueryParams: {
          pageNum: 1,
          pageSize: 10,
          contacts: null,
          agentName: null,
          gradeId: null,
          gradeIdArray:[],
          tel: null,
          queryProvinceAndCityAndDistrict: null,
          state: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    computed: {
      ...mapState({
        agentGrade: state => state.selectAgentGrade.grade,
        gradeSelectModel: state => state.selectAgentGrade.gradeSelectModel,
        agent: state => state.selectAgent.agent,
        agentSelectModel: state => state.selectAgent.agentSelectModel
      })
    },
    watch: {
      open(newValue, oldValue) {
        this.localOpen = newValue; // 同步父组件的 open 值到本地状态
      },
      localOpen(newValue) {
        if (newValue) {
          this.getList() // 当本地状态变为 false 时，通知父组件
        } else {
          this.cancel()
        }
      }
    },
    methods: {
      selectLoadOptions(node, resolve) {
        var query = {
          regionLevel: node.level + 1,
          parentId: node.value || null
        }
        loadOptions(query).then(response => {
          resolve(response.data);
        });
      },
      /** 查询代理商管理列表 */
      getList() {
        this.loading = true;
        listAgent(this.selectAgentQueryParams).then(response => {
          this.agentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.reset();
        this.$emit('close-select-window');
      },
      // 表单重置
      reset() {
        this.resetForm("queryForm");
        this.selectAgentQueryParams.gradeIdArray=[]
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.selectAgentQueryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.selectAgentQueryParams.gradeIdArray=[]
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        if(selection.length>1 && this.gradeSelectModel==2){
          selection=[]
          this.$refs.agentListTable.clearSelection()
          this.$store.dispatch('selectAgent/cleanAgentData')
          this.$modal.msgError("最多只能选择1条数据")
          return
        }
        selection.map(item => {
          this.$store.dispatch('selectAgent/setAgent', item)
        })
      },
      //选择等级
      openSelectGrade(selectVal) {
        this.gradFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectAgentGrade/cleanAgentGrade')
        this.$store.dispatch('selectAgentGrade/setAgentGradeSelectModel', selectVal)
      },
      closeSelectGrade() {
        this.gradFlag = false;
      },
      //确定等级
      selectedGradeData() {
        this.closeSelectGrade()
        if(this.gradeSelectModel == 2){
            this.form.gradeName = this.agentGrade[0].gradeName
            this.form.gradeId = this.agentGrade[0].id
            this.form.gradeCount = this.agentGrade[0].gradeCount
        }else{
            this.selectAgentQueryParams.gradeName=this.agentGrade.map(item => item.gradeName).join(',')
            this.selectAgentQueryParams.gradeIdArray=this.agentGrade.map(item => item.id)
        }
        this.$store.dispatch('selectAgentGrade/cleanAgentGrade')
      },
      //确定选择数据
      selectData() {
        if (this.agent.length < 1) {
          this.$modal.msgError("请至少选中1条代理")
          return
        }
        this.$emit('selected-data')
      }
    }
  };
</script>
